"use strict";

const Controller = require("egg").Controller;
const fs = require("fs");
const path = require("path");
/**
 * 前端上传文件，需要设置
 * x-csrf-token,
 * Content-Type: multipart/form-data
 * body 设置为 form-data, 里面有个属性 file ,值为选取的文件
 */

class UploadController extends Controller {
  async upload() {
    const { ctx } = this;
    const file = ctx.request.files[0];
    // const name = "egg-multipart-test/" + path.basename(file.filename);
    // console.log("----name---------", name);
    // console.log("-------------", file);
    let dir = path.resolve(__dirname, "../../upload_static");
    // console.log("---存放目录----------", dir + file.filename);
    // fs.readFileSync(file.filepath) 从文件路径读取文件
    fs.writeFile(dir + "/" + file.filename, fs.readFileSync(file.filepath), function (err) {
      if (err) {
        return console.error(err);
      }
      fs.unlink(file.filepath);
      console.log(`写入${file.filename}成功`);
    });
  }
}

module.exports = UploadController;
